/**
 * 同步任务表单组件
 * 用于创建和编辑数据同步任务
 */

import React, { useState, useEffect, useCallback } from 'react';
import {
  Form,
  Input,
  Select,
  InputNumber,
  Switch,
  Button,
  Space,
  Row,
  Col,
  Card,
  Divider,
  Table,
  Tooltip,
  Alert,
  Typography
} from 'antd';
import type { FormInstance } from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  InfoCircleOutlined,
  CheckCircleOutlined
} from '@ant-design/icons';

import type {
  SyncTask,
  SyncTaskCreate,
  SyncFieldMapping
} from '../types/sync';
import {
  SyncType,
  TargetType,
  ScheduleType,
  IncrementalFieldType,
  SyncTypeLabels,
  TargetTypeLabels,
  ScheduleTypeLabels,
  IncrementalFieldTypeLabels
} from '../types/sync';
import type { DataSource } from '../types/datasource';
import { DatabaseType, DatabaseTypeLabels } from '../types/datasource';

const { Option } = Select;
const { TextArea } = Input;
const { Text } = Typography;

interface SyncTaskFormProps {
  task?: SyncTask;
  datasources: DataSource[];
  onSubmit: (values: SyncTaskCreate) => Promise<void>;
  onCancel: () => void;
  loading?: boolean;
}

const SyncTaskForm: React.FC<SyncTaskFormProps> = ({
  task,
  datasources,
  onSubmit,
  onCancel,
  loading = false
}) => {
  const [form] = Form.useForm<SyncTaskCreate>();
  const [fieldMappings, setFieldMappings] = useState<SyncFieldMapping[]>([]);
  const [selectedTargetType, setSelectedTargetType] = useState<TargetType>();
  const [selectedSyncType, setSelectedSyncType] = useState<SyncType>();
  const [selectedScheduleType, setSelectedScheduleType] = useState<ScheduleType>();

  // 初始化表单数据
  useEffect(() => {
    if (task) {
      const formValues = {
        ...task,
        field_mappings: task.field_mappings || []
      };
      form.setFieldsValue(formValues);
      setFieldMappings(task.field_mappings || []);
      setSelectedTargetType(task.target_type);
      setSelectedSyncType(task.sync_type);
      setSelectedScheduleType(task.schedule_type);
    } else {
      // 设置默认值
      form.setFieldsValue({
        sync_type: SyncType.FULL,
        target_type: TargetType.CSV,
        schedule_type: ScheduleType.MANUAL,
        batch_size: 1000,
        is_active: true
      });
      setSelectedSyncType(SyncType.FULL);
      setSelectedTargetType(TargetType.CSV);
      setSelectedScheduleType(ScheduleType.MANUAL);
    }
  }, [task, form]);

  /**
   * 获取可用的数据源（按类型筛选）
   */
  const getAvailableDatasources = useCallback((types?: DatabaseType[]) => {
    return datasources.filter(ds => 
      ds.is_active && 
      (!types || types.includes(ds.type))
    );
  }, [datasources]);

  /**
   * 获取源数据源列表
   */
  const getSourceDatasources = useCallback(() => {
    // 源数据源支持所有数据库类型（除了Kafka）
    return getAvailableDatasources([
      DatabaseType.MYSQL,
      DatabaseType.POSTGRESQL,
      DatabaseType.ORACLE,
      DatabaseType.SQLSERVER,
      DatabaseType.DORIS
    ]);
  }, [getAvailableDatasources]);

  /**
   * 获取目标数据源列表
   */
  const getTargetDatasources = useCallback(() => {
    if (selectedTargetType === TargetType.DORIS) {
      return getAvailableDatasources([DatabaseType.DORIS]);
    } else if (selectedTargetType === TargetType.KAFKA) {
      return getAvailableDatasources([DatabaseType.KAFKA]);
    }
    return [];
  }, [selectedTargetType, getAvailableDatasources]);

  /**
   * 目标类型变化处理
   */
  const handleTargetTypeChange = (value: string) => {
    const targetType = value as TargetType;
    setSelectedTargetType(targetType);

    // 清空相关字段
    form.setFieldsValue({
      target_datasource_id: undefined,
      target_table_name: undefined,
      target_path: undefined
    });
  };

  /**
   * 同步类型变化处理
   */
  const handleSyncTypeChange = (value: string) => {
    const syncType = value as SyncType;
    setSelectedSyncType(syncType);

    // 如果切换到全量同步，清空增量相关字段
    if (syncType === SyncType.FULL) {
      form.setFieldsValue({
        incremental_field: undefined,
        incremental_field_type: undefined
      });
    }
  };

  /**
   * 调度类型变化处理
   */
  const handleScheduleTypeChange = (value: string) => {
    const scheduleType = value as ScheduleType;
    setSelectedScheduleType(scheduleType);

    // 如果切换到手动执行，清空Cron表达式
    if (scheduleType === ScheduleType.MANUAL) {
      form.setFieldsValue({
        cron_expression: undefined
      });
    }
  };

  /**
   * 添加字段映射
   */
  const addFieldMapping = () => {
    const newMapping: SyncFieldMapping = {
      source_field: '',
      target_field: '',
      field_type: 'VARCHAR',
      is_key_field: false,
      sort_order: fieldMappings.length
    };
    setFieldMappings([...fieldMappings, newMapping]);
  };

  /**
   * 删除字段映射
   */
  const removeFieldMapping = (index: number) => {
    const newMappings = fieldMappings.filter((_, i) => i !== index);
    setFieldMappings(newMappings);
  };

  /**
   * 更新字段映射
   */
  const updateFieldMapping = (index: number, field: keyof SyncFieldMapping, value: any) => {
    const newMappings = [...fieldMappings];
    newMappings[index] = { ...newMappings[index], [field]: value };
    setFieldMappings(newMappings);
  };

  /**
   * 表单提交
   */
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const submitData: SyncTaskCreate = {
        ...values,
        field_mappings: fieldMappings.filter(mapping =>
          mapping.source_field && mapping.target_field
        )
      };

      // 如果是CSV类型，清空target_path，让后端自动生成
      if (submitData.target_type === TargetType.CSV) {
        submitData.target_path = undefined;
      }

      await onSubmit(submitData);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  /**
   * 验证任务名称唯一性
   */
  const validateTaskName = async (_: any, value: string) => {
    if (!value) return Promise.resolve();
    
    // 如果是编辑模式且名称未改变，跳过验证
    if (task && task.name === value) {
      return Promise.resolve();
    }
    
    // TODO: 调用API验证名称唯一性
    return Promise.resolve();
  };

  /**
   * 验证Cron表达式
   */
  const validateCronExpression = (_: any, value: string) => {
    if (!value || selectedScheduleType !== ScheduleType.CRON) {
      return Promise.resolve();
    }
    
    // 简单的Cron表达式验证
    const cronRegex = /^(\*|([0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9])|\*\/([0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9])) (\*|([0-9]|1[0-9]|2[0-3])|\*\/([0-9]|1[0-9]|2[0-3])) (\*|([1-9]|1[0-9]|2[0-9]|3[0-1])|\*\/([1-9]|1[0-9]|2[0-9]|3[0-1])) (\*|([1-9]|1[0-2])|\*\/([1-9]|1[0-2])) (\*|([0-6])|\*\/([0-6]))$/;
    
    if (!cronRegex.test(value)) {
      return Promise.reject(new Error('请输入有效的Cron表达式'));
    }
    
    return Promise.resolve();
  };

  // 字段映射表格列定义
  const fieldMappingColumns = [
    {
      title: '源字段',
      dataIndex: 'source_field',
      width: 150,
      render: (value: string, record: SyncFieldMapping, index: number) => (
        <Input
          value={value}
          placeholder="源字段名"
          onChange={(e) => updateFieldMapping(index, 'source_field', e.target.value)}
        />
      )
    },
    {
      title: '目标字段',
      dataIndex: 'target_field',
      width: 150,
      render: (value: string, record: SyncFieldMapping, index: number) => (
        <Input
          value={value}
          placeholder="目标字段名"
          onChange={(e) => updateFieldMapping(index, 'target_field', e.target.value)}
        />
      )
    },
    {
      title: '字段类型',
      dataIndex: 'field_type',
      width: 120,
      render: (value: string, record: SyncFieldMapping, index: number) => (
        <Select
          value={value}
          style={{ width: '100%' }}
          onChange={(val) => updateFieldMapping(index, 'field_type', val)}
        >
          <Option value="VARCHAR">VARCHAR</Option>
          <Option value="INT">INT</Option>
          <Option value="BIGINT">BIGINT</Option>
          <Option value="DECIMAL">DECIMAL</Option>
          <Option value="DATETIME">DATETIME</Option>
          <Option value="TEXT">TEXT</Option>
        </Select>
      )
    },
    {
      title: '主键',
      dataIndex: 'is_key_field',
      width: 80,
      render: (value: boolean, record: SyncFieldMapping, index: number) => (
        <Switch
          checked={value}
          size="small"
          onChange={(checked) => updateFieldMapping(index, 'is_key_field', checked)}
        />
      )
    },
    {
      title: '操作',
      width: 80,
      render: (_, record: SyncFieldMapping, index: number) => (
        <Button
          type="text"
          size="small"
          danger
          icon={<DeleteOutlined />}
          onClick={() => removeFieldMapping(index)}
        />
      )
    }
  ];

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
      scrollToFirstError
    >
      {/* 基本信息 */}
      <Card title="基本信息" size="small" style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="name"
              label="任务名称"
              rules={[
                { required: true, message: '请输入任务名称' },
                { pattern: /^[a-zA-Z0-9_-]+$/, message: '只能包含字母、数字、下划线和横线' },
                { validator: validateTaskName }
              ]}
            >
              <Input placeholder="唯一标识，用于API调用" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="display_name"
              label="显示名称"
              rules={[{ required: true, message: '请输入显示名称' }]}
            >
              <Input placeholder="用于界面显示的友好名称" />
            </Form.Item>
          </Col>
        </Row>
        
        <Form.Item
          name="description"
          label="任务描述"
        >
          <TextArea rows={3} placeholder="描述同步任务的用途和注意事项" />
        </Form.Item>
      </Card>

      {/* 数据源配置 */}
      <Card title="数据源配置" size="small" style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="source_datasource_id"
              label="源数据源"
              rules={[{ required: true, message: '请选择源数据源' }]}
            >
              <Select placeholder="选择源数据源">
                {getSourceDatasources().map(ds => (
                  <Option key={ds.id} value={ds.id}>
                    <Space>
                      <Text>{ds.display_name}</Text>
                      <Text type="secondary">({DatabaseTypeLabels[ds.type]})</Text>
                    </Space>
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="source_table_name"
              label="源表名"
              rules={[{ required: true, message: '请输入源表名' }]}
            >
              <Input placeholder="数据库表名" />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          name="source_query"
          label={
            <Space>
              自定义查询SQL
              <Tooltip title="可选，如果指定则使用此SQL查询数据，否则使用表名">
                <InfoCircleOutlined />
              </Tooltip>
            </Space>
          }
        >
          <TextArea rows={4} placeholder="SELECT * FROM table_name WHERE ..." />
        </Form.Item>
      </Card>

      {/* 目标配置 */}
      <Card title="目标配置" size="small" style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              name="target_type"
              label="目标类型"
              rules={[{ required: true, message: '请选择目标类型' }]}
            >
              <Select onChange={handleTargetTypeChange}>
                {Object.entries(TargetTypeLabels).map(([value, label]) => (
                  <Option key={value} value={value}>{label}</Option>
                ))}
              </Select>
            </Form.Item>
          </Col>

          {(selectedTargetType === TargetType.DORIS || selectedTargetType === TargetType.KAFKA) && (
            <Col span={8}>
              <Form.Item
                name="target_datasource_id"
                label="目标数据源"
                rules={[{ required: true, message: '请选择目标数据源' }]}
              >
                <Select placeholder="选择目标数据源">
                  {getTargetDatasources().map(ds => (
                    <Option key={ds.id} value={ds.id}>
                      <Space>
                        <Text>{ds.display_name}</Text>
                        <Text type="secondary">({DatabaseTypeLabels[ds.type]})</Text>
                      </Space>
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          )}

          <Col span={8}>
            {selectedTargetType === TargetType.CSV && (
              <Form.Item
                label="CSV文件"
              >
                <Alert
                  message="CSV文件将自动生成"
                  description="同步完成后，系统会自动生成CSV文件，您可以在任务列表中下载"
                  type="info"
                  showIcon
                />
              </Form.Item>
            )}

            {selectedTargetType === TargetType.DORIS && (
              <Form.Item
                name="target_table_name"
                label="目标表名"
                rules={[{ required: true, message: '请输入目标表名' }]}
              >
                <Input placeholder="Doris表名" />
              </Form.Item>
            )}

            {selectedTargetType === TargetType.KAFKA && (
              <Form.Item
                name="target_path"
                label="Topic名称"
                rules={[{ required: true, message: '请输入Kafka Topic名称' }]}
              >
                <Input placeholder="kafka_topic_name" />
              </Form.Item>
            )}
          </Col>
        </Row>
      </Card>

      {/* 同步配置 */}
      <Card title="同步配置" size="small" style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              name="sync_type"
              label="同步类型"
              rules={[{ required: true, message: '请选择同步类型' }]}
            >
              <Select onChange={handleSyncTypeChange}>
                {Object.entries(SyncTypeLabels).map(([value, label]) => (
                  <Option key={value} value={value}>{label}</Option>
                ))}
              </Select>
            </Form.Item>
          </Col>

          {selectedSyncType === SyncType.INCREMENTAL && (
            <>
              <Col span={8}>
                <Form.Item
                  name="incremental_field"
                  label="增量字段"
                  rules={[{ required: true, message: '请输入增量字段名' }]}
                >
                  <Input placeholder="时间戳字段或自增ID字段" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  name="incremental_field_type"
                  label="字段类型"
                  rules={[{ required: true, message: '请选择字段类型' }]}
                >
                  <Select>
                    {Object.entries(IncrementalFieldTypeLabels).map(([value, label]) => (
                      <Option key={value} value={value}>{label}</Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  name="incremental_start_value"
                  label="增量起始值"
                  tooltip="可选，指定增量同步的起始值。如果不设置，系统将从最后一次同步的位置继续"
                >
                  <Input placeholder="例如：2024-01-01 00:00:00 或 1000" />
                </Form.Item>
              </Col>
            </>
          )}

        </Row>

        <Row gutter={16}>
          <Col span={selectedSyncType === SyncType.INCREMENTAL ? 12 : 16}>
            <Form.Item
              name="batch_size"
              label="批处理大小"
              rules={[
                { required: true, message: '请输入批处理大小' },
                { type: 'number', min: 1, max: 10000, message: '批处理大小必须在1-10000之间' }
              ]}
            >
              <InputNumber
                style={{ width: '100%' }}
                placeholder="每批处理的记录数"
                min={1}
                max={10000}
              />
            </Form.Item>
          </Col>

          {selectedSyncType === SyncType.INCREMENTAL && (
            <Col span={12}>
              <Form.Item
                name="last_incremental_value"
                label="最后增量值"
                tooltip="系统自动维护，显示最后一次成功同步的增量值"
              >
                <Input disabled placeholder="系统自动更新" />
              </Form.Item>
            </Col>
          )}
        </Row>
      </Card>

      {/* 调度配置 */}
      <Card title="调度配置" size="small" style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="schedule_type"
              label="调度类型"
              rules={[{ required: true, message: '请选择调度类型' }]}
            >
              <Select onChange={handleScheduleTypeChange}>
                {Object.entries(ScheduleTypeLabels).map(([value, label]) => (
                  <Option key={value} value={value}>{label}</Option>
                ))}
              </Select>
            </Form.Item>
          </Col>

          {selectedScheduleType === ScheduleType.CRON && (
            <Col span={12}>
              <Form.Item
                name="cron_expression"
                label={
                  <Space>
                    Cron表达式
                    <Tooltip title="格式：分 时 日 月 周，例如：0 2 * * * 表示每天凌晨2点执行">
                      <InfoCircleOutlined />
                    </Tooltip>
                  </Space>
                }
                rules={[
                  { required: true, message: '请输入Cron表达式' },
                  { validator: validateCronExpression }
                ]}
              >
                <Input placeholder="0 2 * * *" />
              </Form.Item>
            </Col>
          )}
        </Row>

        <Form.Item
          name="is_active"
          label="启用状态"
          valuePropName="checked"
        >
          <Switch checkedChildren="启用" unCheckedChildren="禁用" />
        </Form.Item>
      </Card>

      {/* 字段映射 */}
      <Card 
        title={
          <Space>
            字段映射
            <Tooltip title="配置源字段到目标字段的映射关系，如果不配置则使用相同字段名">
              <InfoCircleOutlined />
            </Tooltip>
          </Space>
        }
        size="small" 
        style={{ marginBottom: 16 }}
        extra={
          <Button
            type="dashed"
            size="small"
            icon={<PlusOutlined />}
            onClick={addFieldMapping}
          >
            添加映射
          </Button>
        }
      >
        {fieldMappings.length > 0 ? (
          <Table
            columns={fieldMappingColumns}
            dataSource={fieldMappings}
            pagination={false}
            size="small"
            rowKey={(record, index) => index!}
          />
        ) : (
          <Alert
            message="暂无字段映射"
            description="如果不配置字段映射，系统将使用相同的字段名进行映射"
            type="info"
            showIcon
          />
        )}
      </Card>

      {/* 操作按钮 */}
      <div style={{ textAlign: 'right' }}>
        <Space>
          <Button onClick={onCancel}>
            取消
          </Button>
          <Button
            type="primary"
            htmlType="submit"
            loading={loading}
            icon={<CheckCircleOutlined />}
          >
            {task ? '更新任务' : '创建任务'}
          </Button>
        </Space>
      </div>
    </Form>
  );
};

export default SyncTaskForm;
